package com.ams.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author yuanss
 * @version 1.0
 * @description 实现自动注入通用字段接口
 * @date 2023/11/19 13:22:00
 */
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        insertOrUpdateFill(metaObject, true);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        insertOrUpdateFill(metaObject, false);
    }

    private void insertOrUpdateFill(MetaObject metaObject, boolean isInsert) {
        if (isInsert) {
            //设置创建时间
            if  (Objects.isNull(getFieldValByName("createTime",metaObject))){
                this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
            }
            //设置更新时间
            if  (Objects.isNull(getFieldValByName("updateTime",metaObject))){
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
//            if (!Objects.isNull(getFieldValByName("deleted",metaObject))){
//                this.setFieldValByName("deleted", 0, metaObject);
//            }
        } else {
            //设置更新时间
            if (Objects.isNull(getFieldValByName("updateTime",metaObject))) {
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
        }
    }
}


